package services

import (
	"errors"
	"gorm.io/gorm"
	"mishop/models"
	"mishop/utils"
)

type ICategoryService interface {
	FindByID(category_id uint) (*models.Category, error)
	FindByCategoryID(page, rows int, parent_id uint) (*models.Pages, error)
	Create(c *models.Category) (*models.Category, error)
	Update(c *models.Category) (*models.Category, error)
	Delete(category_id int) error
}
type CategoryService struct {
	model models.ICategory
}

func (p *CategoryService) Delete(category_id int) error {
	return p.model.Delete(category_id)
}

func (p *CategoryService) Update(c *models.Category) (*models.Category, error) {
	_, err := p.model.FindByID(c.ID)
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, errors.New("分类未找到")
	}
	//判断名称是否存在
	name, err := p.model.FindByName(c.Name)
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	if name != nil {
		return nil, errors.New("分类名称已存在")
	}
	return p.model.Update(c)
}

func (p *CategoryService) Create(c *models.Category) (*models.Category, error) {
	//判断是否存在name相同的
	find, err := p.model.FindByName(c.Name)
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	if find != nil {
		return nil, errors.New("分类名称已存在")
	}
	return p.model.Create(c)
}

func (p *CategoryService) FindByPage(page, rows int, parent_id uint) ([]*models.Category, error) {
	panic("")
}

func (p *CategoryService) FindByID(category_id uint) (*models.Category, error) {
	return p.model.FindByID(category_id)
}

func (p *CategoryService) FindByCategoryID(page, rows int, parent_id uint) (*models.Pages, error) {
	page,rows = utils.ProcessPagesEntity(page,rows)
	return p.model.FindByCategoryID(page, rows, parent_id)
}

func NewCategoryService(model models.ICategory) ICategoryService {
	return &CategoryService{model: model}
}
